package com.example.chatapp.service;

import com.example.chatapp.common.BusinessException;
import com.example.chatapp.manager.RedisCacheManager;
import com.example.chatapp.model.User;
import com.example.chatapp.repository.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 用户认证服务
 * 职责：处理用户登录、登出、房间切换等业务逻辑
 */
@Service
public class AuthService {
    
    private final RedisCacheManager cacheManager;
    private final UserRepository userRepository;
    private final BCryptPasswordEncoder passwordEncoder;
    private static final Duration ONLINE_TTL = Duration.ofMinutes(30);
    
    public AuthService(RedisCacheManager cacheManager, UserRepository userRepository) {
        this.cacheManager = cacheManager;
        this.userRepository = userRepository;
        this.passwordEncoder = new BCryptPasswordEncoder();
    }
    
    /**
     * 用户注册
     */
    public User register(String username, String password) {
        // 参数校验
        if (username == null || username.trim().isEmpty()) {
            throw new BusinessException(400, "用户名不能为空");
        }
        if (password == null || password.length() < 6) {
            throw new BusinessException(400, "密码长度至少为6位");
        }
        
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new BusinessException(400, "用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPasswordHash(passwordEncoder.encode(password));
        user.setCreatedAt(LocalDateTime.now());
        
        return userRepository.save(user);
    }
    
    /**
     * 验证用户密码
     */
    public User authenticate(String username, String password) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException(401, "用户名或密码错误"));
        
        if (!passwordEncoder.matches(password, user.getPasswordHash())) {
            throw new BusinessException(401, "用户名或密码错误");
        }
        
        return user;
    }
    
    /**
     * 用户登录
     */
    public void login(String username, String roomId) {
        // 业务逻辑：可以在这里添加密码验证、用户权限检查等
        
        // 设置在线状态
        cacheManager.setUserOnline(username, roomId, ONLINE_TTL);
        
        System.out.println("[AuthService] User " + username + " logged in to room: " + roomId);
    }
    
    /**
     * 切换房间
     */
    public void switchRoom(String username, String newRoomId) {
        // 业务逻辑：可以添加房间权限验证
        
        // 更新在线状态
        cacheManager.setUserOnline(username, newRoomId, ONLINE_TTL);
        
        System.out.println("[AuthService] User " + username + " switched to room: " + newRoomId);
    }
    
    /**
     * 用户登出
     */
    public void logout(String username) {
        // 业务逻辑：可以添加清理用户相关数据的操作
        
        // 移除在线状态
        cacheManager.removeUserOnline(username);
        
        System.out.println("[AuthService] User " + username + " logged out");
    }
    
    /**
     * 获取用户所在房间
     */
    public String getUserRoom(String username) {
        return cacheManager.getUserRoom(username);
    }
    
    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(String username) {
        return cacheManager.getUserRoom(username) != null;
    }
    
    /**
     * 获取指定房间的在线用户列表
     */
    public java.util.List<String> getOnlineUsersInRoom(String roomId) {
        return cacheManager.getOnlineUsersInRoom(roomId);
    }
}
